package com.jwgf.smarowindingmachine_unity.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jwgf.adapter.CommonAdapter;
import com.jwgf.adapter.ViewHolder;
import com.jwgf.fault.FaultRecorder;
import com.jwgf.smarowindingmachine_unity.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;

import androidx.fragment.app.DialogFragment;

public class TitleBarDialog extends DialogFragment {

	public static final String KEY = "fault_keys";
	private ListView list;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		ArrayList<Integer> listFault = getArguments().getIntegerArrayList(KEY);
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		LayoutInflater inflater = getActivity().getLayoutInflater();

		View v = inflater.inflate(R.layout.list_view, null);
		list = (ListView) v.findViewById(R.id.list);

		List<Map<String, String>> listData = new ArrayList<Map<String,String>>();

		for (Integer code: listFault) {
            Map<String, String> row = new HashMap<String, String>();
            row.put("code", Integer.toHexString(code));
            row.put("string", FaultRecorder.getInstance().getFault(code));
            listData.add(row);
		}

		CommonAdapter<Map<String, String>> adapter = new CommonAdapter<Map<String, String>>(
				getActivity(), listData, R.layout.dialog_array_item) {

			@Override
			public void convert(ViewHolder holder, final Map<String, String> item) {
				holder.setText(R.id.array_item, item.get("string"));
				holder.getView(R.id.array_item).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
                        int code = Integer.valueOf(item.get("code"), 16);
                        DialogFragment dlg = new FaultDetailDialog();
                        Bundle args = new Bundle();
                        args.putInt(FaultDetailDialog.FAULT_CODE, code);
                        dlg.setArguments(args);
                        dlg.show(getFragmentManager(), "fault_detail");
					}
				});
			}
		};
		list.setAdapter(adapter);
		builder.setTitle(R.string.fault_record);
		builder.setView(v);
		return builder.create();
	}

}
